package 力扣链表;

public class Leetcode203删除链表所有值为val的节点 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(3,null);
        ListNode node2 = new ListNode(3,node1);
        ListNode node3 = new ListNode(2,node2);
        ListNode node4 = new ListNode(1,node3);
        ListNode node5 = new ListNode(1,node4);
//        ListNode node6 = new ListNode(1,node5);
        ListNode node = removeElements(node2, 2);
        while (node != null){
            System.out.println(node.val);
            node = node.next;
        }
    }
    //递归解法
    public static ListNode removeElements(ListNode head, int val) {
        if (head == null){
            return null;
        }
        head.next = removeElements(head.next,val);
        if (head.val == val){
            return head.next;
        }
        return head;
    }
    //虚拟头节点
    public static ListNode removeElement1(ListNode head, int val) {
        ListNode dummyHead= new ListNode();
        dummyHead.next = head;
        while (dummyHead.next != null){
            if (dummyHead.next.val == val){
                dummyHead.next = dummyHead.next.next;
            }else {
                dummyHead = dummyHead.next;
            }
        }
        return head;
    }
    public static ListNode removeElements2(ListNode head, int val) {
        while(head != null && head.val == val){
            head = head.next;
        }
        if(head == null){
            return null;
        } else{
            ListNode node = head;
            while (node.next != null){
                if(node.next.val == val){
                    node.next = node.next.next;
                }else{
                    node = node.next;
                    if (node == null){
                        break;
                    }
                }
            }
            return head;
        }
    }
}

